const fs = require('fs');
const path = require('path');
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');

module.exports = exports = {};

function load_db(datadir, dbname='zether.json') {
  if (!datadir || !fs.existsSync(datadir)) {
    throw `datadir not found: ${datadir}`;
  }
  const db_path = path.join(datadir, dbname);
  if (!fs.statSync(db_path).isFile()) {
    throw `db file not found: ${db_path}`;
  }
  const db = low(new FileSync(db_path));
  db.defaults({
    'inner-product-verifiers': [],
    'burn-verifiers': [],
    'transfer-verifier-inners': [],
    'transfer-verifiers': [],
    zethers: {}, // owner -> zth contracts
    zthaccs: {}, // yhash -> zth accounts
  }).write();

  return db;
}

exports.load_db = load_db;
